$(function() {
    let layer = layui.layer
    let form = layui.form
    let laypage = layui.laypage;
    template.defaults.imports.dataFormat = function(date) {
        return moment(date).format('YYYY-MM-DD hh:mm:ss')
    }




    //定义查询参数
    let q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
    }


    initTable()

    function initTable() {
        $.ajax({
            method: 'GET',
            url: '/my/article/list',
            data: q,
            success(res) {
                if (res.status !== 0) {
                    return layer.msg('获取失败！')
                }
                let htmlStr = template('tpl-table', res)
                $('tbody').html(htmlStr)

                //渲染分页
                renderPage(res.total)
            }
        })
    }

    //渲染select
    initCate()

    function initCate() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success(res) {
                if (res.status !== 0) return layer.msg('初始化文章分类失败！')
                let htmlStr = template('tpl-cate', res)
                $('[name=cate_id]').html(htmlStr)
                form.render()
            }
        })
    }

    $('#search').on('submit', function(e) {
        e.preventDefault()
        let cate_id = $('[name=cate_id]').val()
        let state = $('[name=state]').val()
        q.cate_id = cate_id
        q.state = state
        initTable()
    })



    //渲染分页
    function renderPage(total) {
        laypage.render({
            elem: 'pageBox',
            count: total,
            limit: q.pagesize,
            curr: q.pagenum,
            layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
            limits: [2, 3, 5, 10],
            jump(obj, first) {
                q.pagenum = obj.curr
                q.pagesize = obj.limit
                if (!first) {
                    initTable()
                }
            }
        })
    }


    //删除
    $('tbody').on('click', '.btn-delet', function() {
        let len = $('.btn-delet').length
        let id = $(this).attr('data-id')
        layer.confirm('是否删除?', {
            icon: 3,
            title: '提示'
        }, function(index) {
            //do something
            $.ajax({
                method: 'GET',
                url: '/my/article/delete/' + id,
                success(res) {
                    if (res.status !== 0) return layer.msg('删除文章失败！')
                    layer.msg('删除文章成功！')
                    if (len == 1) {
                        //判断
                        q.pagenum = q.pagenum === 1 ? q.pagenum : q.pagenum--
                    }
                    initTable()
                }
            })
            layer.close(index);
        });
    })
})